package cn.baker.rabbitmq.task;

import cn.baker.rabbitmq.config.TransRabbitProperties;
import cn.baker.rabbitmq.entity.TransMessage;
import cn.baker.rabbitmq.service.TransMessageService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 重新发送发送失败的消息
 * @author yuanyu
 */
@Slf4j
public class ResendTask {

    private TransMessageService transMessageService;

    private RabbitTemplate transRabbitTemplate;

    private TransRabbitProperties transRabbitProperties;

    public ResendTask(TransMessageService transMessageService, RabbitTemplate transRabbitTemplate, TransRabbitProperties transRabbitProperties) {
        this.transMessageService = transMessageService;
        this.transRabbitTemplate = transRabbitTemplate;
        this.transRabbitProperties = transRabbitProperties;
    }

    /**
     * 定时任务
     */
    @Scheduled(fixedDelayString = "${trans.rabbitmq.producer.resendFreq:3000}")
    public void resendMessage() {
        List<TransMessage> transMessageList = transMessageService.listReadyMessages();
        if (transMessageList.isEmpty()) {
            log.debug("@mqLog 定时任务开始执行,待重发消息为空");
            return;
        }
        log.info("@mqLog 定时任务开始执行, 重新发送消息, transMessageList:[{}]", JSON.toJSONString(transMessageList));
        for (TransMessage transMessage : transMessageList) {
            if (transMessage.getSequence() > transRabbitProperties.getProducer().getResendTimes()) {
                log.error("@mqLog message resend too many times! transMessage:[{}]", JSON.toJSONString(transMessage));
                transMessageService.messageDead(transMessage.getId());
                continue;
            }
            //设置消息属性
            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setContentType("application/json");
            Message message = new Message(transMessage.getPayload().getBytes(), messageProperties);
            message.getMessageProperties().setMessageId(transMessage.getId());
            //发送
            transRabbitTemplate.convertAndSend(transMessage.getExchange(), transMessage.getRoutingKey(), message, new CorrelationData(transMessage.getId()));
            transMessageService.messageResend(transMessage.getId());
        }
    }
}
